<script setup lang="ts">
import { createVNode, onMounted, ref, watch } from "vue";
import {
  afterPrintAddApi,
  afterPrintDeleteApi,
  afterPrintExport,
  afterPrintSelectOneApi,
  afterPrintUpdateApi,
  pageQueryApi,
} from "@/api/afterPrint";
import { message, Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";

const loading = ref(true);
//分页
const pagination = ref({
  total: undefined,
  current: undefined,
  pageSize: undefined,
});
//
onMounted(async () => {
  await search();
  await searchEquipment();
});
const searchEquipment = async () => {
  const res = await equipmentSelectAll();
  options.value = res.data;
};
//查询条件
const queryInfo = ref({
  page: pagination.value.current,
  pageSize: pagination.value.pageSize,
  taskCode: "",
  targetCode: "",
  sendEquipmentID: "",
  sendEquipmentName: "",
  startTime: "",
  endTime: "",
});
//表格数据
const data = ref([]);
const columns = [
  {
    title: "TaskCode",
    dataIndex: "taskCode",
    key: "taskCode",
  },
  {
    title: "订单号",
    dataIndex: "targetCode",
    key: "targetCode",
  },
  {
    title: "材料",
    dataIndex: "material",
    key: "material",
  },
  {
    title: "尺寸",
    dataIndex: "size",
    key: "size",
  },
  {
    title: "数量",
    dataIndex: "number",
    key: "number",
  },
  {
    title: "设备",
    dataIndex: "sendEquipmentName",
    key: "sendEquipmentName",
  },
  {
    title: "时间",
    dataIndex: "createTime",
    key: "createTime",
  },
  {
    title: "操作",
    dataIndex: "operation",
    key: "operation",
  },
];
//切换页码
const handleTableChange = (pag: { pageSize: number; current: number }) => {
  queryInfo.value.page = pag.current;
  queryInfo.value.pageSize = pag.pageSize;
  queryPageAfterPrint();
};
//查询
const search = async () => {
  loading.value = true;
  const res = await pageQueryApi(queryInfo.value);
  data.value = res.data.records;
  pagination.value = {
    total: res.data.total,
    current: res.data.current,
    pageSize: res.data.size,
  };
  loading.value = false;
};
//删除Modal
const showDeleteConfirm = (id: number) => {
  Modal.confirm({
    title: "确认删除数据？",
    icon: createVNode(ExclamationCircleOutlined),
    okText: "确认",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      const res = await afterPrintDeleteApi({
        id: id,
      });
      if (res) {
        message.success("删除成功");
        await queryPageAfterPrint();
      }
    },
  });
};
//搜索表单
const searchFormInfo = ref({
  taskCode: "",
  targetCode: "",
  startTime: "",
  endTime: "",
});
const reset = () => {
  searchFormInfo.value = {
    taskCode: "",
    targetCode: "",
    startTime: "",
    endTime: "",
  };
  queryInfo.value = {
    taskCode: "",
    endTime: "",
    material: "",
    TargetCode: "",
    page: 0,
    pageSize: 10,
    startTime: "",
  };
  time.value = null;
  value.value = "选择设备";
  queryPageAfterPrint();
};
const time = ref<RangeValue>();
// 如果 time 的值是从后端返回的，需要进行时区转换
watch(time, (newVal, oldVal) => {
  if (newVal !== null) {
    const start = dayjs(newVal[0]);
    const end = dayjs(newVal[1]);
    //将时间转为 dayjs 对象并设置为 UTC+8 时区
    searchFormInfo.value.startTime = start.format();
    searchFormInfo.value.endTime = end.format();
  } else {
    searchFormInfo.value.startTime = "";
    searchFormInfo.value.endTime = "";
  }
});
//添加和删除模态框
const afterPrintModelOpen = ref(false);
const afterPrintInfo = ref({
  id: undefined,
  material: undefined,
  number: undefined,
  sendEquipmentID: undefined,
  size: undefined,
  targetCode: undefined,
  taskCode: undefined,
});
//编辑
const handleEdit = async (id: number) => {
  title.value = "修改";
  afterPrintInfo.value = {
    id: undefined,
    material: undefined,
    number: undefined,
    sendEquipmentID: undefined,
    size: undefined,
    targetCode: undefined,
    taskCode: undefined,
  };
  const res = await afterPrintSelectOneApi(id);
  afterPrintInfo.value = res.data;
  editEuipId.value = res.data.sendEquipmentID;
  afterPrintModelOpen.value = true;
};
const afterPrintModelOk = async () => {
  console.log(title.value);
  if (title.value === "添加") {
    const res = await afterPrintAddApi(afterPrintInfo.value);
    if (res) {
      message.success("添加成功");
      afterPrintModelOpen.value = false;
      await queryPageAfterPrint();
    }
  } else if (title.value === "修改") {
    const res = await afterPrintUpdateApi(afterPrintInfo.value);
    if (res) {
      message.success("修改成功");
      afterPrintModelOpen.value = false;
      await queryPageAfterPrint();
    }
  }
};
//添加
const title = ref("");
const addAfterPrintModel = async () => {
  afterPrintModelOpen.value = true;
  title.value = "添加";
  afterPrintInfo.value = {
    id: undefined,
    material: undefined,
    number: undefined,
    sendEquipmentID: undefined,
    size: undefined,
    targetCode: undefined,
    taskCode: undefined,
  };
  editEuipId.value = "选择设备";
};
const editEuipId = ref(undefined);
const editHandleChange = (value: string) => {
  afterPrintInfo.value.sendEquipmentID = value;
};
//设备选择
import type { SelectProps } from "ant-design-vue";
import { equipmentSelectAll } from "@/api/equipment";
import { RangeValue } from "ant-design-vue/es/vc-picker/interface";
import dayjs from "dayjs";

const value = ref("选择设备");
const options = ref<SelectProps["options"]>([]);
const handleChange = (value: string) => {
  queryInfo.value.sendEquipmentID = value;
  queryPageAfterPrint();
};
//搜索
const queryPageAfterPrint = async () => {
  queryInfo.value.taskCode = searchFormInfo.value.taskCode;
  queryInfo.value.targetCode = searchFormInfo.value.targetCode;
  queryInfo.value.startTime = searchFormInfo.value.startTime;
  queryInfo.value.endTime = searchFormInfo.value.endTime;
  await search();
};
//导出为Excel
const exportExcelOpen = ref(false);
const exportExcelName = ref("default_name");
const exportExcel = async () => {
  exportExcelOpen.value = true;
};

function blobExportExcel(res: any) {
  if (res instanceof Blob) {
    const blob = new Blob([res], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = downloadUrl;
    link.download = exportExcelName.value;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(downloadUrl);
  }
}

const doExportExcel = async () => {
  const res = await afterPrintExport(queryInfo.value); // 获取二进制响应数据
  blobExportExcel(res);
  exportExcelOpen.value = false;
};
</script>

<template>
  <div>
    <!--  搜索表单-->
    <a-form :model="searchFormInfo" layout="inline">
      <a-form-item label="TaskCode">
        <a-input v-model:value="searchFormInfo.taskCode" />
      </a-form-item>
      <a-form-item label="订单号">
        <a-input v-model:value="searchFormInfo.targetCode" />
      </a-form-item>
      <a-form-item label="时间">
        <a-space direction="vertical" :size="12">
          <a-range-picker v-model:value="time" show-time />
        </a-space>
      </a-form-item>
      <a-space>
        <a-select
          ref="select"
          v-model:value="value"
          style="width: 120px"
          :options="options"
          @change="handleChange"
          :field-names="{
            label: 'equipmentName',
            value: 'equipmentID',
          }"
        >
        </a-select>
      </a-space>
      <a-divider type="vertical" />
      <a-button type="default" @click="reset">重置</a-button>
      <a-divider type="vertical" />
      <a-button type="primary" @click="queryPageAfterPrint">搜索</a-button>
      <div style="margin-left: auto">
        <a-button type="link" @click="exportExcel">导出为excel</a-button>
        <a-modal
          v-model:open="exportExcelOpen"
          title="导出文件名"
          @ok="doExportExcel"
        >
          <a-input v-model:value="exportExcelName" />
        </a-modal>
        <a-divider type="vertical" />

        <a-button type="primary" @click="addAfterPrintModel">添加</a-button>
        <!--        <a-divider type="vertical" />-->
        <!--        <a-button danger @click="() => (deleteOpen = true)">快捷删除</a-button>-->
      </div>
    </a-form>
  </div>
  <div id="AfterPrintData">
    <!--  表格-->
    <a-table
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'operation'">
          <a-button default @click="() => handleEdit(record.id)">编辑</a-button>
          <a-divider type="vertical" />
          <a-button danger @click="showDeleteConfirm(record.id)">删除</a-button>
        </template>
      </template>
    </a-table>
  </div>
  <!--  添加数据-->
  <div>
    <a-modal
      v-model:open="afterPrintModelOpen"
      v-model:title="title"
      @ok="afterPrintModelOk"
    >
      <a-form-item label="TaskCode">
        <a-input v-model:value="afterPrintInfo.taskCode" />
      </a-form-item>
      <a-form-item label="订单号">
        <a-input v-model:value="afterPrintInfo.targetCode" />
      </a-form-item>
      <a-form-item label="材料">
        <a-input v-model:value="afterPrintInfo.material" />
      </a-form-item>
      <a-form-item label="尺寸">
        <a-input v-model:value="afterPrintInfo.size" />
      </a-form-item>
      <a-form-item label="数量">
        <a-input v-model:value="afterPrintInfo.number" />
      </a-form-item>
      <a-form-item label="设备">
        <a-select
          ref="select"
          v-model:value="editEuipId"
          style="width: 120px"
          :options="options"
          @change="editHandleChange"
          :field-names="{
            label: 'equipmentName',
            value: 'equipmentID',
          }"
        >
        </a-select>
      </a-form-item>
    </a-modal>
  </div>
</template>

<style scoped></style>
